import { fromJS } from 'immutable';
import { getHotSingerListRequest, getSingerListRequest } from '../../../api/request';
import { CHANGE_ENTER_LOADING, CHANGE_PAGE_COUNT, CHANGE_PULLDOWN_LOADING, CHANGE_PULLUP_lOADING, CHANGE_SINGER_LIST } from './constants';

const changeSingerList = (data) => ({
  type: CHANGE_SINGER_LIST,
  data: fromJS(data)
});

export const changePageCount = (data) => ({
  type: CHANGE_PAGE_COUNT,
  data
});

export const changeEnterLoading = (data) => ({
  type: CHANGE_ENTER_LOADING,
  data
});

export const changePullUpLoading = (data) => ({
  type: CHANGE_PULLUP_lOADING,
  data
});

export const changePullDownLoading = (data) => ({
  type: CHANGE_PULLDOWN_LOADING,
  data
});

// 第一次加载热门歌手
export const getHotSingerList = () => {
  return (dispatch) => {
    getHotSingerListRequest(0).then((res) => {
      const data = res.artists;
      dispatch(changeSingerList(data));
      dispatch(changeEnterLoading(false));
      dispatch(changePullDownLoading(false));
    }).catch(() => {
      console.log('热门歌手数据获取失败');
    }); 
  };
};

// 加载更多热门歌手
export const refreshMoreHotSingerList = () => {
  return (dispatch, getState) => {
    const pageCount = getState()['singers'].get('pageCount');
    const singerList = getState()['singers'].get('singerList').toJS();
    
    getHotSingerListRequest(pageCount).then((res) => {
      const data = [...singerList, ...res.artists];
      dispatch(changeSingerList(data));
      dispatch(changePullUpLoading(false));
    }).catch(() => {
      console.log('热门歌手数据获取失败');
    });
  };
};

// 第一次加载对应类别的歌手
export const getSingerList = (type, area, alpha) => {
  return (dispatch, getState) => {
    getSingerListRequest(type, area, alpha, 0).then((res) => {
      const data = res.artists;
      console.log(data);
      dispatch(changeSingerList(data));
      dispatch(changeEnterLoading(false));
      dispatch(changePullDownLoading(false));
      dispatch(changePageCount(data.length));
    }).catch(() => {
      console.log('歌手数据获取失败');
    });
  };
};

// 加载更多歌手
export const refreshMoreSingerList = (type, area, alpha) => {
  return (dispatch, getState) => {
    const pageCount = getState()['singers'].get('pageCount');
    const singerList = getState()['singers'].get('singerList').toJS();
    getSingerListRequest(type, area, alpha, pageCount).then((res) => {
      const data = [...singerList, ...res.artists];
      dispatch(changeSingerList(data));
      dispatch(changePullUpLoading(false));
      dispatch(changePageCount(data.length));
    }).catch(() => {
      console.log('热门歌手数据获取失败');
    });
  };
};